<template>
  <base-breadcrumb v-loading="loading">
    <div class="about-master-container">
      <a-card>
        <title-name title="基础信息"></title-name>
        <BForm
          ref="form"
          :config="formConfig"
          :form="form"
          :rule="rules"
        />
      </a-card>

      <a-card>
        <title-name title="一票否决"></title-name>
        <b-table
          :show-page="false"
          ref="table"
          :columns="columns"
          :request="loadDataVetoDTOS"
        >
          <template slot="veto" slot-scope="text, record">
            <a class="requiredFormItem">
              <BSelect
                v-model="record.veto" :list="[{id:1,name:'是'},{id:0,name:'否'}]" :disabled="disabled"
                @change="calcNextCanEdit"
              />
            </a>
          </template>
        </b-table>
      </a-card>

      <a-card>
        <title-name title="考核表"></title-name>
        <div style="display:flex;align-items: center;margin: 20px 0;">
          <span>得分：</span>
          <BaseInput v-model="form.score" style="width: 200px;" disabled />
        </div>
        <b-table
          :show-page="false"
          ref="table2"
          :columns="columns2"
          :request="loadDataCheckDTOS"
        >
          <template slot="view" slot-scope="text, record">
            <div v-html="text"></div>
          </template>
          <template slot="realScore" slot-scope="text, record">
            <BaseInputNumber
              class="requiredFormItem"
              v-model="record.realScore"
              :min="0"
              :max="record.shouldScore"
              @blur="calc"
              :disabled="disabled||nextDisabled"
            />
          </template>
        </b-table>
      </a-card>

      <a-card>
        <title-name :title="title2"></title-name>
        <BaseTextarea v-model="form.opinion" class="requiredFormItem" :disabled="disabled" />
      </a-card>

      <div class="tar page-btn-right-top">
<!--        <a-button v-if="!disabled" type="primary" @click="save('DRAFT')" class="mr20">保存草稿</a-button>-->
        <a-button v-if="!disabled" type="primary" @click="save('SUBMITTED')" class="mr20">提交</a-button>
        <a-button v-checkVisibleInDetail @click="$close">关闭</a-button>
      </div>
    </div>


  </base-breadcrumb>
</template>
<script>
import BSelect from '@/components/BComponents/BSelect'
import { getSubcontractor } from '@/api/businessAffairs/sml'
import api from '@/api/safetySupervision/subcontractorComment'
import subcontractorLevelApi from '@/api/safetySupervision/base/constructionStage.js'
import SelectSubcontractor from '@/components/Select/SelectSubcontractor'

export default {
  name: 'edit',
  components: {},
  props: {
    lType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      columns: [
        { title: '一票否决项', dataIndex: 'name' },
        { title: '是否', dataIndex: 'veto', width: 150, scopedSlots: { customRender: 'veto' } }
      ],
      loadDataVetoDTOS: p => {
        return { code: 200, data: this.form.vetoDTOS }
      },
      columns2: [
        { title: '考核内容', dataIndex: 'name', width: 200 },
        { title: '考核要求', dataIndex: 'view', scopedSlots: { customRender: 'view' } },
        { title: '应得分', dataIndex: 'shouldScore', width: 200 },
        { title: '实得分', dataIndex: 'realScore', width: 200, scopedSlots: { customRender: 'realScore' } }
      ],
      loadDataCheckDTOS: p => {
        return { code: 200, data: this.form.checkDTOS }
      },
      loading: false,
      form: {
        id: null,
        score: null,
        orgId: '',
        orgName: '',
        vetoDTOS: [],
        checkDTOS: [],
        creatorLevel: this.$currentPost().code,
        creatorName: this.$userInfo().name,
        createTime: this.$dateFormat(Date.now(), 'D'),
        type: 1
      },
      rules: {
        yearMon: [{ required: true, message: '请选择', trigger: 'change' }],
        subId: [{ required: true, message: '请选择被考核单位', trigger: 'change' }],
        cataId: [{ required: true, message: '请选择分包单位引进级别', trigger: 'change' }],
        cataDetailsId: [{ required: true, message: '请选择分包单位类型', trigger: 'change' }]
      },
      nextDisabled: false,
      disabled: this.$route.query.pageType === 'look'
    }
  },
  computed: {
    title2() {
      if (this.lType === 1) return '安监部门意见'
      if (this.lType === 2) return '分公司安监部门意见'
      if (this.lType === 3) return '项目安监部门意见'
    },
    formConfig() {
      return [
        {
          row: true,
          children: [
            { type: 'input', value: 'orgName', label: '考核单位', attrs: { disabled: true } },
            {
              type: BSelect, value: 'yearMon', label: '年度',
              show: this.lType === 1,
              attrs: {
                request: () => {
                  let r = Array.from({ length: 50 }).map((v, i) => {
                    return { id: new Date().getFullYear() - i, name: new Date().getFullYear() - i }
                  })
                  return { code: 200, data: r }
                },
                disabled: this.disabled
              }
            },
            {
              type: 'month-picker', value: 'yearMon', label: '月份',
              show: this.lType === 2 || this.lType === 3,
              attrs: {
                disabled: this.disabled,
                valueFormat: 'YYYY-MM'
              }
            }
          ]
        },
        {
          row: true,
          children: [
            {
              type: BSelect, value: 'subId', label: '被考核单位',
              show: this.lType === 1,
              attrs: {
                keys: ['subContractorId', 'name'],
                request: () => {
                  let data = {};
                  data.isAll = true;
                  return getSubcontractor(data)
                },
                disabled: this.disabled
              },
              on: {
                selectChange: e => {
                  if (e) {
                    this.form.name = e.name
                  }
                }
              }
            },
            {
              type: BSelect, value: 'subId', label: '被考核单位',
              show: this.lType === 2,
              attrs: {
                form: this.form,
                keyValue: 'orgId',
                keys: ['subContractorId', 'name'],
                init: false,
                request: e => {
                  let data = {
                    id: e,
                    isAll:true
                  }
                  return api.subContractorList(data)
                },
                disabled: this.disabled
              },
              on: {
                selectChange: e => {
                  if (e) {
                    this.form.name = e.name
                  }
                }
              }
            },
            {
              type: SelectSubcontractor, value: 'subId', label: '被考核单位',
              show: this.lType === 3,
              attrs: {
                form: this.form,
                keyValue: 'orgId',
                disabled: this.disabled,
                isAll:true,
              },
              on: {
                selectChange: e => {
                  if (e) {
                    this.form.name = e.name
                  }
                }
              }
            },
            {
              type: BSelect, value: 'cataId', label: '分包单位引进级别',
              attrs: {
                disabled: this.disabled,
                request: async () => {
                  let res = await subcontractorLevelApi.list({}, { type: 2, 'haveTree': false })
                  return { code: 200, data: res.data.filter(v => v.status === 0) }
                }
              }
            },
            {
              type: BSelect, value: 'cataDetailsId', label: '分包单位类型',
              attrs: {
                init: false,
                form: this.form,
                keyValue: 'cataId',
                disabled: this.disabled,
                request: k => {
                  return subcontractorLevelApi.findListByDetails({}, { type: 2, cataId: k })
                }
              }
            },
            { type: 'input', value: 'creatorName', label: '填报人', attrs: { disabled: true } },
            { type: 'input', value: 'createTime', label: '填报日期', attrs: { disabled: true } }
          ]
        }
      ]
    }
  },
  watch: {},
  mounted() {
    this.form.type = this.lType
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      this.getData()
    } else {
      this.getType()
      if (this.form.type === 1 || this.form.type === 2) {
        this.form.orgId = this.$currentPost().orgId
        this.form.orgName = this.$currentPost().orgName
      }
      if (this.form.type === 3) {
        this.form.orgId = this.$currentPost().projectId
        this.form.orgName = this.$currentPost().projectName
      }
    }
  },

  methods: {
    calcNextCanEdit() {
      this.nextDisabled = this.form.vetoDTOS.some(v => v.veto === 1)
      if (this.nextDisabled) {
        this.form.score = 0
        this.form.checkDTOS.map(v => v.realScore = '')
      }
    },
    calc() {
      this.form.score = 0
      this.form.checkDTOS.map(v => {
        this.form.score += v.realScore
      })
    },
    async getType() {
      this.loading = true
      let res = await api.getSubEvaluateVeto({ type: this.form.type })
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        res.data.vetoDTOS.map((v, i) => {
          v.id = 'a' + Date.now() + i
        })
        res.data.checkDTOS.map((v, i) => {
          v.id = 'a' + Date.now() + i + i
        })
        this.form.vetoDTOS = res.data.vetoDTOS
        this.form.checkDTOS = res.data.checkDTOS
        this.$refs.table.refresh()
        this.$refs.table2.refresh()
      }
    },
    async getData() {
      this.loading = true
      let res = await api.findListByMainId({ id: this.form.id })
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.form = res.data
        this.calc()
        this.form.vetoDTOS.map(v => {
          v.veto = v.veto ? 1 : 0
        })
        this.calcNextCanEdit()
        this.$refs.table.refresh()
        this.$refs.table2.refresh()
      }
    },
    async save(status) {
      this.$console(this.form)
      return new Promise(async resolve => {
        this.$refs.form.validate(async valid => {
          if (valid) {
            if (!this.form.opinion) {
              return this.$noticeWarning('请填写意见！')
            }
            let temp = this.$clone(this.form)
            temp.auditStatus = status
            temp.vetoDTOS.map(v => {
              v.veto = v.veto === 1
              v.vetoStr = v.veto ? '是' : '否'
              if (!temp.id){
                delete v.id
              }
            })
            temp.checkDTOS.map(v => {
              if (!temp.id){
                delete v.id
              }
            })
            temp.createTime = ''
            this.loading = true
            let res
            if (temp.id) {
              res = await api.editByMain({}, temp)
            } else {
              res = await api.createByMain({}, temp)
            }
            this.loading = false
            if (res.code === this.SUCCESS_CODE) {
              this.$noticeSuccess('保存成功')
              this.$close()
              resolve(true)
            }
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.status {
  margin-left: 30px;
  padding: 20px;
  margin-bottom: 20px;
  background: rgb(244, 249, 255);
  color: #000;

  .text {
    font-size: 25px;
    color: rgb(2, 167, 240);
  }
}
</style>
